import Vue from 'vue'
import VueRouter from 'vue-router'

// 路由懒加载
// 1、 login / home / Welcome为一组
const Login = () =>
    import ( /* webpackChunkName: "Login_Home_Welcome"*/ './../components/Login')
const Home = () =>
    import ( /* webpackChunkName: "Login_Home_Welcome"*/ './../components/Home')
const Welcome = () =>
    import ( /* webpackChunkName: "Login_Home_Welcome"*/ './../components/Welcome')

// 2、 Users / Rights / Roles为一组
const Users = () =>
    import ( /* webpackChunkName: "Users_Rights_Roles"*/ './../components//users/Users')
const Rights = () =>
    import ( /* webpackChunkName: "Users_Rights_Roles"*/ './../components/power/Rights')
const Roles = () =>
    import ( /* webpackChunkName: "Users_Rights_Roles"*/ './../components/roles/Roles')

// 3、 Cate / Params为一组
const Cate = () =>
    import ( /* webpackChunkName: "Cate_Params"*/ './../components/goods/Cate')
const Params = () =>
    import ( /* webpackChunkName: "Cate_Params"*/ './../components/goods/Params')

// 4、 GoodsList / Add为一组
const GoodsList = () =>
    import ( /* webpackChunkName: "GoodsList_Add"*/ './../components/goods/List')
const Add = () =>
    import ( /* webpackChunkName: "GoodsList_Add"*/ './../components/goods/Add')

// 5、 Orders / Report为一组
const Orders = () =>
    import ( /* webpackChunkName: "Orders_Report"*/ './../components/order/Orders')
const Report = () =>
    import ( /* webpackChunkName: "Orders_Report"*/ './../components/report/Report')

Vue.use(VueRouter)

const routes = [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    {
        path: '/home',
        component: Home,
        redirect: '/welcome',
        children: [
            { path: '/welcome', component: Welcome },
            { path: '/users', component: Users },
            { path: '/rights', component: Rights },
            { path: '/roles', component: Roles },
            { path: '/categories', component: Cate },
            { path: '/params', component: Params },
            { path: '/goods', component: GoodsList },
            { path: '/goods/add', component: Add },
            { path: '/orders', component: Orders },
            { path: '/reports', component: Report }

        ]
    }
]

const router = new VueRouter({
    routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
    // to 将要访问的路径
    // from 代表从哪个路径跳转而来
    // next 是一个函数，表示放行
    //     next() 放行 ； next('login') 强制跳转
    if (to.path === '/login') return next() //如果跳转到login，则直接放行
        // 获取token
    const tokenStr = window.sessionStorage.getItem('token')
        // 如果没有token值，则强制跳到登录页面
    if (!tokenStr) return next('/login')
    next()
})

export default router